// signal.js —— 在原有签名逻辑基础上，加入自动会话 & 两步提交 —— //

(async function() {
    const SECRET_KEY = 'PZ123';  // 与后端保持一致

    // 生成签名（双层 MD5）
    function genSign(ts) {
        const raw = SECRET_KEY + ts;
        const first = CryptoJS.MD5(raw).toString();
        return CryptoJS.MD5(first).toString();
    }

    // 获取页面元素
    const cargoBtn = document.getElementById('cargoBtn');
    const deckBtn  = document.getElementById('deckBtn');
    const cargoIn  = document.getElementById('cargoInput');
    const deckIn   = document.getElementById('deckInput');
    const resultEl = document.getElementById('result');
    const sessionEl= document.getElementById('sessionId');

    let sessionId = null;

    // —— 自动开启会话 —— //
    async function startSession() {
        const ts = Date.now().toString();
        const sign = genSign(ts);

        try {
            const resp = await fetch('/smart-ship/start', {
                method: 'POST',
                headers: { 'timestamp': ts, 'sign': sign }
            });
            const body = await resp.json();
            if (body.code === 1) {
                sessionId = body.data;
                sessionEl.value = sessionId;
                console.log('sessionId=', sessionId);
            } else {
                throw new Error(body.msg);
            }
        } catch (e) {
            alert('会话初始化失败：' + e.message);
        }
    }

    // —— 上传货物 —— //
    async function uploadCargo() {
        if (!sessionId) return alert('Session 未就绪，请刷新后重试');
        let payload;
        try {
            payload = JSON.parse(cargoIn.value);
        } catch {
            return alert('Cargo JSON 格式错误');
        }
        const ts = Date.now().toString(), sign = genSign(ts);
        try {
            const resp = await fetch(`/smart-ship/${sessionId}/cargo`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'timestamp': ts,
                    'sign': sign
                },
                body: JSON.stringify(payload)
            });
            const body = await resp.json();
            if (body.code === 1) {
                alert('货物上传成功');
            } else {
                throw new Error(body.msg);
            }
        } catch (e) {
            alert('上传货物出错：' + e.message);
        }
    }

    // —— 上传甲板并触发装载 —— //
    async function uploadDeck() {
        if (!sessionId) return alert('Session 未就绪，请刷新后重试');
        let payload;
        try {
            payload = JSON.parse(deckIn.value);
        } catch {
            return alert('Deck JSON 格式错误');
        }
        const ts = Date.now().toString(), sign = genSign(ts);
        try {
            const resp = await fetch(`/smart-ship/${sessionId}/deck`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'timestamp': ts,
                    'sign': sign
                },
                body: JSON.stringify(payload)
            });
            const body = await resp.json();
            if (body.code === 1) {
                resultEl.textContent = JSON.stringify(body.data, null, 2);
            } else {
                throw new Error(body.msg);
            }
        } catch (e) {
            alert('装载请求出错：' + e.message);
        }
    }

    // 入口：页面加载后自动启动会话，并绑定事件
    window.addEventListener('DOMContentLoaded', async () => {
        await startSession();
        cargoBtn.addEventListener('click', uploadCargo);
        deckBtn .addEventListener('click', uploadDeck);
    });
})();
